<template>
  <div class="balance-record-page">
    <!-- 固定背景 -->
    <div class="fixed-bg">
      <div class="tab-bg">
        <img
          v-if="tab === 'income'"
          class="tab-bg-img"
          src="/src/assets/images/tab-bg1.png"
          alt=""
        />
        <img
          v-if="tab === 'expense'"
          class="tab-bg-img"
          src="/src/assets/images/tab-bg2.png"
          alt=""
        />
        <img
          v-if="tab === 'note'"
          class="tab-bg-img"
          src="/src/assets/images/tab-bg3.png"
          alt=""
        />
      </div>

      <!-- 固定标签栏 -->
      <div class="wallet-tabs">
        <div
          :class="['wallet-tab', { active: tab === 'income' }]"
          @click="switchTab('income')"
        >
          {{ t("products_income") }}
        </div>
        <div
          :class="['wallet-tab', { active: tab === 'expense' }]"
          @click="switchTab('expense')"
        >
          {{ t("balancerecord_expense") }}
        </div>
        <div
          :class="['wallet-tab', { active: tab === 'note' }]"
          @click="switchTab('note')"
        >
          {{ t("withdrawal_note") }}
        </div>
        <div class="tab-underline" :style="underlineStyle"></div>
      </div>
    </div>

    <!-- 滚动内容 -->
    <div class="scrollable-content">
      <div class="record-list">
        <van-list
          v-model:loading="loading"
          :finished="finished"
          :loading-text="t('index_loading')"
          :finished-text="t('index_noMoreData')"
          :offset="10"
          @load="loadMoreData"
        >
          <template v-if="recordList.length > 0">
            <div
              v-for="(item, index) in recordList"
              :key="item.id"
              class="record-card"
            >
              <div class="record-icon">
                <img :src="iconForTab" alt="icon" />
              </div>
              <div class="record-info">
                <div class="record-title">{{ t(item.title) }}</div>
                <div class="record-time">{{ item.writedate }}</div>
              </div>
              <div class="record-amount">
                {{ item.number }}
              </div>
            </div>
          </template>
          <NoData v-if="recordList.length === 0 && !loading" />
        </van-list>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from "vue";
import NoData from "@/components/NoData.vue";
import { financeList } from "@/api/user";
import { showToast } from "vant";

const tab = ref("income");
const tabIconMap = {
  income: new URL("@/assets/images/icn1.png", import.meta.url).href,
  expense: new URL("@/assets/images/icn2.png", import.meta.url).href,
  note: new URL("@/assets/images/icn3.png", import.meta.url).href,
};
const iconForTab = computed(() => tabIconMap[tab.value]);

// 接口参数相关变量
const pageSize = 15;
const currentPage = ref(1);
const loading = ref(false);
const finished = ref(false);
const isFirstLoad = ref(true);
const recordList = ref<any[]>([]);
const { t } = useI18n();

// 将tab转换为接口需要的type参数
const getTypeFromTab = (tabValue: string) => {
  switch (tabValue) {
    case "income":
      return "1";
    case "expense":
      return "2";
    case "note":
      return "3";
    default:
      return "1";
  }
};

// 加载资产记录数据
async function loadRecordData() {
  try {
    loading.value = true;
    const res = await financeList({
      type: getTypeFromTab(tab.value),
      page: currentPage.value.toString(),
      limit: pageSize.toString(),
    });

    if (res.code === 200) {
      const list = res.data || [];

      // 如果是第一页，则替换数据，否则追加数据
      if (currentPage.value === 1) {
        recordList.value = list;
      } else {
        recordList.value = [...recordList.value, ...list];
      }

      // 判断是否还有更多数据
      if (list.length < pageSize) {
        finished.value = true;
      } else {
        currentPage.value++;
      }
    } else {
      showToast(res.msg || t("balancerecord_getFail"));
      finished.value = true;
    }
  } catch (error) {
    console.error("err", error);
    showToast(t("products_networkError"));
    finished.value = true;
  } finally {
    loading.value = false;
    isFirstLoad.value = false;
  }
}

// 加载更多数据
function loadMoreData() {
  // 首次加载时不执行loadMore，避免重复请求
  if (isFirstLoad.value) {
    isFirstLoad.value = false;
    loading.value = false;
    return;
  }
  loadRecordData();
}

// 切换标签
function switchTab(newTab: string) {
  if (tab.value === newTab) return;

  tab.value = newTab;
  currentPage.value = 1;
  finished.value = false;
  isFirstLoad.value = true;
  recordList.value = [];
  loadRecordData();
}

const tabIndexMap = { income: 0, expense: 1, note: 2 };
const underlineStyle = computed(() => {
  const idx = tabIndexMap[tab.value];
  return {
    "--tab-index": idx,
  };
});

// 组件挂载时加载数据
onMounted(() => {
  loadRecordData();
});
</script>

<style scoped>
.balance-record-page {
  min-height: 100vh;
  overflow: hidden;
  font-size: 17px;
  color: #f6eade;
  position: relative;
  display: flex;
  flex-direction: column;
}

/* 使用伪元素固定背景 */
.balance-record-page::before {
  content: "";
  position: fixed;
  top: 56px;
  left: 0;
  width: 100%;
  height: 100%;
  background: url("../../assets/images/user/topBg.png") no-repeat top;
  background-size: 100% auto;
  z-index: -1;
}

.fixed-bg {
  position: fixed;
  top: 56px;
  left: 0;
  width: 100%;
  z-index: 10;
  background-color: #221a18;
}

.tab-bg {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  z-index: 0;
  display: flex;
  justify-content: center;
  pointer-events: none;
}

.tab-bg-img {
  width: 100%;
  height: auto;
  aspect-ratio: 750 / 770;
  object-fit: cover;
}

.wallet-tabs {
  display: flex;
  position: relative;
  background: none;
  height: 55px;
  justify-content: space-around;
  align-items: center;
  z-index: 1;
}

.scrollable-content {
  margin-top: 70px;
  /* overflow-y: auto; */

  /* height: calc(100vh - 70px); */

  position: relative; /* 使其创建新的层叠上下文 */
  z-index: 1; /* 确保内容在背景上面 */
}

.wallet-tab {
  flex: 1;
  text-align: center;
  font-size: 17px;
  color: #b9b1a9;
  font-weight: 500;
  padding-bottom: 10px;
  cursor: pointer;
  position: relative;
  transition: color 0.2s;
  z-index: 1;
  overflow: visible;
}

.wallet-tab.active {
  color: #fff;
  font-weight: 700;
}

.wallet-tab .star {
  color: #ffd700;
  margin-left: 2px;
}

.tab-underline {
  position: absolute;
  bottom: 10px;
  height: 3px;
  width: 20px;
  background: #f6eade;
  border-radius: 2px;
  transition: left 0.3s;
  z-index: 2;
  left: calc((100% / 3) * var(--tab-index, 0) + (100% / 3 - 20px) / 2);
}

.record-list {
  padding: 0 0 16px 0;
}

.record-card {
  display: flex;
  align-items: center;
  background: rgba(254, 242, 230, 0.1);
  border-radius: 18px;
  margin: 0 16px 16px 16px;
  padding: 16px 18px;
  box-shadow: 0 2px 8px 0 rgba(0, 0, 0, 0.08);
}
.record-icon {
  width: 50px;
  height: 50px;
  margin-right: 10px;
  padding-top: 15px;
  display: flex;
  align-items: center;
  justify-content: center;
}
.record-icon img {
  width: 101px;
  height: 101px;
}
.record-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
}
.record-title {
  font-size: 16px;
  color: #fff;
  font-weight: 600;
  margin-bottom: 2px;
}
.record-time {
  font-size: 13px;
  color: #b9b1a9;
}
.record-amount {
  font-size: 18px;
  margin-left: 12px;
  min-width: 80px;
  text-align: right;
  font-weight: 700;
  color: #f6eade;
}
</style>
